<?php

namespace common\models\app;

use Yii;
use common\helpers\ArrayHelper;

/**
 * This is the model class for table "{{%app_client}}".
 *
 * @property int $id
 * @property string $name 应用ID
 * @property string $secret 密钥
 * @property string $descirption 备注
 * @property int $status 状态
 * @property string $created_at 创建时间
 * @property string $updated_at 更新时间
 */
class AppClient extends \common\db\ActiveRecord {

    use \common\traits\Constants;

    const STATUS_DELETED = -1;
    const STATUS_DEFAULT = 0;
    const STATUS_ACTIVE = 10;

    /**
     * {@inheritdoc}
     */
    public static function tableName() {
        return '{{%app_client}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules() {
        return [
            [['name', 'secret'], 'required'],
            [['status', 'created_at', 'updated_at'], 'integer'],
            [['name', 'secret'], 'string', 'max' => 32],
            [['descirption'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'id' => 'ID',
            'name' => '应用ID',
            'secret' => '密钥',
            'descirption' => '备注',
            'status' => '状态',
            'created_at' => '创建时间',
            'updated_at' => '更新时间',
        ];
    }

    public static function findByAppId($appid) {
        return static::findOne(['name' => $appid]);
    }

    public function validateSignature($params, &$signature) {
        $sign = ArrayHelper::remove($params, 'sign');
        $nonce = ArrayHelper::remove($params, 'nonce');
        ksort($params);
        $string = implode('', $params);
        $signature = hash('sha256', $this->secret . $string . $nonce);
        return $signature === $sign;
    }

}
